require "prawn"
require 'prawn/layout' 
class PdfGeneratorController < ApplicationController
  
  before_filter :init_data
  rescue_from Exception, :with => :render_error

  def render_error(exception)
    logger.info "User logged : #{current_user.inspect}"
    log_error(exception)
    render :template => "/errors/error.html.erb"
  end

  def Strategy
    logger.info ("Generating pdf report for lead strategy coordinator. Role id #{@role.id} Report id :#{@report_response.report.id}, ReportResponse id:#{@report_response.id}")
    maps=ReportsController.strategy_coordinator_view(@role,@report_response)
    coordinate_types_question_map=maps[0]
    coordinate_types_role_map=maps[1]
    cant_max_people=0
    coordinate_types_role_map.values.each{|set_roles|
      if set_roles.length > cant_max_people
        cant_max_people=set_roles.length
      end
    }
    
    width=(300+cant_max_people*50)
    file=Tempfile.new "strategy.pdf"
    Prawn::Document.generate file.path , :page_size =>  [width, 841.89]  do |pdf|
      pdf.font "#{Prawn::BASEDIR}/data/fonts/DejaVuSans.ttf"
      pdf.text "STRATEGY COORDINATOR REPORT" , :size => 15, :align => :center
      pdf.text "#{report_period_time(@report_response.report_request)}", :size => 12, :align => :center
      pdf.text "\n#{@role.strategy.name}", :size => 12, :align => :center
      pdf.text "\nLegend: No O   Partial P   Yes/Complete yes   Not applicable- NA\n\n" , :size => 8
      
      headers=["Indicator by Strategy","SC-#{@role.strategy.id}"]
      name=Strategy.name
      question_map=coordinate_types_question_map[name]
      data=create_data_for_line(question_map,coordinate_types_role_map[name])
      if data.length>0
            pdf.table data,
            :font_size  => 8, 
            :headers            => headers,
            :column_widths => { 0 => 250, 1 => 50 },
            :align_headers      => :center
        end
      
      pdf.text "\n\n"
      
      headers=["COUNTRY COORDINATORS"]
      col_width={0=>250}
      cont=1
      name=Country.name
        coordinate_types_role_map[name].each{|aux_role|
        headers.push(["#{aux_role.country.name[0,10]}"])
        col_width[cont]=70
        cont=cont+1
      }
      
      question_map=coordinate_types_question_map[name]
      data=create_data_for_line(question_map,coordinate_types_role_map[name])
      if data.length>0
            pdf.table data,
            :font_size  => 8, 
            :headers            => headers,
            :column_widths => col_width,
            :align_headers      => :center
        end
        
      pdf.text "\n\n"
      headers=["CROSS-BORDERS"]
      col_width={0=>250}
      cont=1
      name=Site.name
      coordinate_types_role_map[name].each{|aux_role|
        headers.push("XB-#{aux_role.id}")
        col_width[cont]=50
        cont=cont+1
      }
      
      question_map=coordinate_types_question_map[name]
      data=create_data_for_line(question_map,coordinate_types_role_map[name])
      if data.length>0
        pdf.table data,
        :font_size  => 8, 
        :headers            => headers,
        :column_widths => col_width,
        :align_headers      => :center
      end
    end
    send_file file.path, :type => 'application/pdf', :disposition => 'inline',:filename=>"strategy.pdf"
  end
  
  def create_data_for_line(question_map,set_roles)
    data=Array.new
    question_map.each{|question,role_map|
      aux_array=Array.new
      if question.is_yes_no
        question_text=question.text_for(role_map.keys[0])
        aux_array.push("#{question.code} #{question_text}")
        set_roles.each{|aux_role|
          answer=role_map[aux_role]
          if not answer.nil?
            if answer.is_yes
              aux_array.push("●")
            else
               aux_array.push("O")
           end
         else
           aux_array.push("")
         end
        }
        data.push(aux_array)
      end
    }
    return data
  end
  
  
  
  def Site     
    logger.info "Generating pdf report for cross border. Role id #{@role.id} Report id :#{@report_response.report.id}, ReportResponse id:#{@report_response.id}"
    file=Tempfile.new "site.pdf"
    Prawn::Document.generate file.path , :page_size => 'B4'  do |pdf|
      pdf.font "#{Prawn::BASEDIR}/data/fonts/DejaVuSans.ttf"
      pdf.text "#{xb_info(@role.site)}" , :size => 15, :align => :center
      pdf.text "#{report_period_time(@report_response.report_request)}", :size => 15, :align => :center
      pdf.text "\nReferences: Yes:●  No:O\n", :size => 8
      
      @report_response.report.groupings.each{|group|
        yes_no_q_data=Array.new
        text_q_data=Array.new
        pdf.text "\n #{group.text}\n\n", :size => 12
        group.questions_for_role(@role).each {|question|
          if question.is_yes_no
            yes_no_q_data.push(write_question_yesno_xb(question))
          else
            text_q_data.push(write_question_text_xb(question))
          end
        }
    
       if yes_no_q_data.length>0
            pdf.table yes_no_q_data,
            :font_size  => 8, 
            :position           => :center,
            :headers            => ["Indicators, by Strategy","Yes/No","Comment"],
            :column_widths => { 0 => 250, 1 => 50, 2 => 350 },
            :align_headers      => :center
        end
        
        if text_q_data.length>0
          puts text_q_data.inspect
          pdf.table text_q_data,     
            :font_size  => 8, 
            :position           => :center,
            :headers            => ["Indicators, by Strategy","Comment"],
            :column_widths => { 0 => 250, 1 => 400 },
            :align_headers      => :center  
        end
      }
    end
    send_file file.path, :type => 'application/pdf', :disposition => 'inline',:filename=>"site.pdf"
  end

  def Country
    logger.info "Generating pdf report for country coordinator. Role id #{@role.id} Report id :#{@report_response.report.id}, ReportResponse id:#{@report_response.id}"
    coordinated_xbs=@report_response.owner_role.coordinated_xbs
    headers=["Indicator by strategy","CC"]
    column_widths = {0=>250,1=>30}
    xb_columns=Array.new
    cont=2
    coordinated_xbs.each do |xb|
      headers.push("XB-#{xb.site.cross_borders.map(&:number).join(',')}")
      column_widths[cont]=37
      cont+=1
    end
    headers.push("# of Yes")
    column_widths[cont]=45
    
    width=50
    column_widths.values.each{|w| width=width+w}

    file=Tempfile.new "country.pdf"
    Prawn::Document.generate file.path , :page_size =>  [width, 841.89]  do |pdf|
      pdf.font "#{Prawn::BASEDIR}/data/fonts/DejaVuSans.ttf"
      pdf.text "COUNTRY: #{@role.country.name}" , :size => 15, :align => :center
      pdf.text "#{report_period_time(@report_response.report_request)}", :size => 12, :align => :center
      pdf.text "\n\nLegend: Yes ●  No O  Not applicable- NA" , :size => 8
      
      @report_response.report.groupings.reject {|x| x.strategy.nil?}.each do |group|
        data=Array.new
        pdf.text "\n #{group.text}\n\n", :size => 10
        group.questions_for_role(@role).each do |question|
          aux_array=Array.new
          title_position=0
          question_text=question.text_for(@role)
          aux_array.push("#{question.code} #{question_text}")
          first_column=(question.for_role(@role)).first_column
          if question.is_yes_no
            aux_array+=write_question_yesno_cc(first_column,question,coordinated_xbs)
            data.push(aux_array)
          else 
            if question.is_option
              (headers.length - 1).times do
                aux_array.push("")
              end
              data.push(aux_array)
              write_question_option_cc(@report_response,question).each {|array|data.push(array)}
            end
          end
        end
        if data.length>0
          pdf.table data,     
            :font_size  => 8, 
            :position           => :center,
            :headers            => headers,
            :column_widths => column_widths,
            :align_headers      => :center  
        end
      end
    end
    send_file file.path, :type => 'application/pdf', :disposition => 'inline',:filename=>"country.pdf"
  end
  
  
  private 
  
  def write_question_yesno_cc(first_column,question,coordinated_xbs)
    aux_array=Array.new
    yes_responses=0
    if first_column == 'yes'
      if @report_response.answer_or_default(question).is_yes
          aux_array.push("●")
        else
          aux_array.push("O")
      end
    else
      aux_array.push("NA")
    end
    
    coordinated_xbs.each do |xb|
      xb_answer = @report_response.xb_answer question, xb
      if not xb_answer.nil?
        if xb_answer.is_yes
          aux_array.push("●")
          yes_responses=yes_responses+1
        elsif xb_answer.is_no
          aux_array.push("O")
        else
           aux_array.push("-")
        end
      else            
         aux_array.push("NA")  
      end  
    end
    if first_column == 'auto'
      aux_array.push(yes_responses)
    else
      aux_array.push("")
    end
    return aux_array
  end
  
  def xb_info(site)
    site_xb = "#{site.name} - #{site.matching_names}"
    country_name=site.country.name
    city_name=site.city
    "XB SITE: #{site_xb}    Country - #{country_name}    Province - #{city_name}"
  end
  
  def report_period_time(report_request)
  #For 6-month period from Year - 2009         Month - June             to Year - 2009              Month - December
    year_from=report_request.period_start.year
    month_period_from=report_request.period_start.month
    year_to=report_request.period_end.year
    month_period_to=report_request.period_end.month
    month_map={1 => "January", 6 => "June", 7=> "July", 12 => "December"}
    result ="6 month period from Year - #{year_from}  Month - #{month_map[month_period_from]}  to Year - #{year_to}  Month - #{month_map[month_period_to]}"
    return result
  end
 

  def write_question_text_xb(question)
    aux_array=Array.new
    aux_array.push(question.text_for(@role))
    aux_array.push(@report_response.answer(question).value_text)       
    return aux_array
  end  

  def write_question_yesno_xb(question)
    aux_array=Array.new
    question_text=question.text_for(@role)
    aux_array.push("#{question.code} #{question_text}")   
    answer=@report_response.answer(question)
    if answer.is_no
      aux_array.push ("O")
    elsif answer.is_yes
      aux_array.push("●")
    else
      aux_array.push("-")
    end
    aux_array.push(answer.value_text)
    return aux_array
  end

  def init_data
    @report_response = ReportResponse.find_by_id params[:id]
    render :nothing => true, :status => 404 and return false if @report_response.nil? 
    render :nothing => true, :status => 403 and return false if !@report_response.owner_users.include?(current_user) and not current_user.is_admin?
    @role=@report_response.owner_role
  end
  
  def write_question_option_cc(report_response,question)
    aux_array=Array.new
    answer = report_response.cc_answer question
    if not question.text_for( report_response.owner_role ).nil?
      question.options.each do |question_option|
        line=Array.new
        line=["#{question_option.code} - #{question_option.text}"]
        if not answer.nil?
          line.push(cc_answer_for_cc(question_option,answer))
        else
          line.push("NA")
        end
        report_response.owner_role.coordinated_xbs.each do |xb|
          line.push(xb_answer_for_cc(report_response,question,question_option,xb))
        end
        line.push("")
        aux_array.push(line)
      end
    end
    return aux_array
  end
  
  def cc_answer_for_cc (question_option,answer)
    line=Array.new
    state = answer.state_for question_option
    show_yes = state
    show_no = (not state.nil? and not state)
    if show_yes
        line.push("●")
    elsif show_no
      line.push("O")
    else
      line.push("")
    end
    return line
  end
  
  def xb_answer_for_cc(report_response,question,question_option,xb)
    line=Array.new    
    xb_answer = report_response.xb_answer question, xb
    if not xb_answer.nil?
      state = xb_answer.state_for question_option
      show_yes = state
      show_no = (not state.nil? and not state)
      if show_yes
        line.push("●")
      elsif show_no
        line.push("O")
      else
        line.push("")
      end
    else
      line.push("")
    end
    return line
  end
end